from info import constants, db
from info.models import User, News, Category
from info.response_code import RET
from info.utils.common import login_user_data
from datetime import datetime, timedelta
from . import admin_blu
from sqlalchemy import extract
from flask import render_template, request, session, redirect, url_for, g, jsonify


# 增加和修改新闻分类
@admin_blu.route('/add_category', methods=["POST"])
def add_category():
    """修改或者添加分类"""
    # 接收参数
    category_id = request.json.get("id")
    category_name = request.json.get("name")
    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 判断是否有分类id
    if category_id:
        category = Category.query.get(category_id)
        if not category:
            return jsonify(errno=RET.NODATA, errmsg="未查询到分类信息")
        category.name = category_name
    else:
        # 如果没有分类id，则是添加分类
        category = Category()
        category.name = category_name
        # 新增分类信息
        db.session.add(category)

    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="保存数据成功")


# 新闻分类
@admin_blu.route('/news_category')
def news_category():
    # 获取所有的分类信息
    categorys = Category.query.filter(Category.id != 1).all()
    return render_template('admin/news_type.html', categorys=categorys)


# 新闻详细信息
@admin_blu.route('/news_edit_detail/<int:news_id>', methods=['GET', 'POST'])
def news_edit_detail(news_id):
    if request.method == 'GET':
        # 获取参数 news_id
        # 查询新闻是否存在
        news = News.query.get(news_id)
        if not news:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "未查询到此新闻"})
        # 分类 和 新闻
        categories = Category.query.filter(Category.id != 1).all()
        # 筛选出当前分类和分类列表是否能匹配上
        categories_li = []
        for category in categories:
            c_dict = category.to_dict()
            c_dict["is_selected"] = False
            if category.id == news.category_id:
                c_dict["is_selected"] = True
            categories_li.append(c_dict)
        # news 新闻 以及categories 新闻分类传递给页面
        data = {"news": news.to_dict(), "categories": categories_li}
        return render_template('admin/news_edit_detail.html', data=data)
    else:
        news_id = request.form.get("news_id")
        title = request.form.get("title")
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")
        # 1.1 判断数据是否有值
        if not all([title, digest, content, category_id]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        news = News.query.get(news_id)
        if not news:
            return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")

        # 1.2 尝试读取图片
        if index_image:
            try:
                index_image = index_image.read()
            except Exception as e:
                return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

            # 2. 将标题图片上传到七牛
            # try:
            #     key = storage(index_image)
            # except Exception as e:
            #     current_app.logger.error(e)
            #     return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
            # news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        # 3. 设置相关数据
        news.title = title
        news.digest = digest
        news.content = content
        news.category_id = category_id

        # 4. 保存到数据库
        db.session.commit()
        # 5. 返回结果
        return jsonify(errno=RET.OK, errmsg="编辑成功")


# 创建一个新闻编辑路由
@admin_blu.route('/news_edit')
def news_edit():
    """返回新闻列表"""

    page = request.args.get("p", 1)
    keywords = request.args.get("keywords", "")
    try:
        page = int(page)
    except Exception as e:
        page = 1

    news_list = []
    current_page = 1
    total_page = 1

    filters = []
    # 如果有关键词
    if keywords:
        # 添加关键词的检索选项
        filters.append()

    # 查询
    paginate = News.query.filter(*filters) \
        .order_by(News.create_time.desc()) \
        .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

    news_list = paginate.items
    current_page = paginate.page
    total_page = paginate.pages

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    context = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list": news_dict_list}

    return render_template('admin/news_edit.html', data=context)


# 管理员审核详情路由
@admin_blu.route('/news_review_detail/<int:news_id>', methods=['GET', 'POST'])
def news_review_detail(news_id):
    if request.method == 'GET':
        # news_id 新闻id已经有了
        news = News.query.get(news_id)
        if not news:
            return render_template('admin/news_review_detail.html',
                                   data={"errmsg": "未查询到此新闻"})
        # 如果新闻有内容就显示页面
        data = {"news": news.to_dict()}
        return render_template('admin/news_review_detail.html', data=data)
    else:
        # 1.获取参数
        news_id = request.json.get("news_id")
        action = request.json.get("action")

        # 2.判断参数
        if not all([news_id, action]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        if action not in ("accept", "reject"):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        # 3.查询新闻
        news = News.query.get(news_id)

        if not news:
            return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

        # 4.根据不同的状态设置不同的值
        if action == "accept":
            news.status = 0
        else:
            # 拒绝通过，需要获取原因
            reason = request.json.get("reason")
            if not reason:
                return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
            news.reason = reason
            news.status = -1

        # 保存数据库
        db.session.commit()
        return jsonify(errno=RET.OK, errmsg="操作成功")


# 管理员审核 页面
@admin_blu.route('/news_review')
def news_review():
    """返回待审核新闻列表"""

    page = request.args.get("p", 1)
    keywords = request.args.get('keywords', '')
    try:
        page = int(page)
    except Exception as e:
        page = 1

    news_list = []
    current_page = 1
    total_page = 1
    # 判断keywords为不为空
    filter_list = [News.status != 0]
    if keywords:
        filter_list.append(News.title.contains(keywords))
    # 分页的条件 News.status 需要审核的新闻  News.create_time按照创建时间做排序
    paginate = News.query.filter(*filter_list) \
        .order_by(News.create_time.desc()) \
        .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

    news_list = paginate.items
    current_page = paginate.page
    total_page = paginate.pages

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    context = {"total_page": total_page, "current_page": current_page, "news_list": news_dict_list}

    return render_template('admin/news_review.html', data=context)


# 用户列表
@admin_blu.route('/user_list')
def user_list():
    # 查询所有用户数据
    """获取用户列表"""

    # 获取参数
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 设置变量默认值
    users = []
    current_page = 1
    total_page = 1

    paginate = User.query.filter(User.is_admin == False) \
        .order_by(User.last_login.desc()) \
        .paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
    users = paginate.items
    current_page = paginate.page
    total_page = paginate.pages

    # 将模型列表转成字典列表
    users_list = []
    for user in users:
        users_list.append(user.to_admin_dict())

    context = {"total_page": total_page, "current_page": current_page, "users": users_list}
    return render_template('admin/user_list.html',
                           data=context)


# 用户页面数据统计
@admin_blu.route('/user_count')
def user_count():
    # 统计所有用户
    user_all_count = User.query.filter(User.is_admin == 0).count()

    # 计算当月用户
    # 2018-07-23
    now_data = datetime.now()
    # 当前年月
    year = now_data.year
    month = now_data.month
    # 通过extract获取数据库中的年 月对比
    month_count = User.query.filter(User.is_admin == 0,
                                    extract('year', User.create_time) == year,
                                    extract('month', User.create_time) == month,
                                    ).count()
    # 当前年月
    day = now_data.day
    # 通过extract获取数据库中的年 月对比
    day_count = User.query.filter(User.is_admin == 0,
                                  extract('year', User.create_time) == year,
                                  extract('month', User.create_time) == month,
                                  extract('day', User.create_time) == day,
                                  ).count()

    # 统计这个月每天用户量
    # 开始时间
    begin_datetime = now_data - timedelta(29)
    cur_count_list = []
    cur_date_list = []
    for i in range(0, 30):
        # 计算每天的量
        cur_date = begin_datetime + timedelta(i)
        # 获取当日用户数量
        cur_count = User.query.filter(User.is_admin == 0,
                                      extract('year', User.create_time) == cur_date.year,
                                      extract('month', User.create_time) == cur_date.month,
                                      extract('day', User.create_time) == cur_date.day,
                                      ).count()
        cur_count_list.append(cur_count)
        # 保存日期 2018-07-01
        cur_date_list.append(cur_date.strftime('%Y-%m-%d'))

    data = {
        "user_all_count": user_all_count,
        "month_count": month_count,
        "day_count": day_count,
        "cur_date_list": cur_date_list,
        "cur_count_list": cur_count_list
    }
    return render_template('admin/user_count.html',
                           data=data)


# 管理员退出
@admin_blu.route('/logout')
def logout():
    session.pop('user_id')
    session.pop('nick_name')
    session.pop('mobile')
    try:
        session.pop('is_admin')
    except Exception as e:
        pass
    # 登出以后跳转到登录页面
    return jsonify(errno=0)


# 管理员首页路由
@admin_blu.route('/index')
@login_user_data
def index():
    user = g.user
    return render_template('admin/index.html', user=user)


# 登录路由
@admin_blu.route('/login', methods=['POST', 'GET'])
def login():
    # 既要get显示页面又要处理post提交
    if request.method == 'GET':
        # 如果管理员登录完成以后再次访问登录 不允许
        user_id = session.get('user_id')
        if not user_id:
            # 如果是空到登录页
            return render_template('admin/login.html')
        else:
            # 如果不是空到管理员首页
            return redirect(url_for('admin.index'))

    else:
        # 针对post提交 用户名 密码 csrf
        username = request.form.get('username')
        password = request.form.get('password')
        # 验证用户名和密码
        if not all([username, password]):
            return render_template('admin/login.html', errmsg='用户名和密码为空')
        # 从数据库查询User有没有这个用户
        user = User.query.filter(User.mobile == username).first()
        # 判断有没有这个用户
        if not user:
            return render_template('admin/login.html', errmsg='用户名和密码错误')
        # 判断密码
        if not user.check_password(password):
            return render_template('admin/login.html', errmsg='用户名和密码错误')
        # 判断是否是管理员
        if not user.is_admin:
            return render_template('admin/login.html', errmsg='你不是管理员')
        # 登录完成 1.记录session 2.跳转页面
        session["user_id"] = user.id
        session["nick_name"] = user.nick_name
        session["is_admin"] = user.is_admin
        session["mobile"] = user.mobile
        # return  redirect('/admin/index')
        return redirect(url_for('admin.index'))
